package com.wxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wxy.config.GetConnectionConfig;
import com.wxy.config.JwtConfig;
import com.wxy.dao.IdConnectionDao;
import com.wxy.eneity.IdConnection;
import com.wxy.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author 47868
 */
@Service("LoginService")
public class LoginServiceImpl implements LoginService {
    private final IdConnectionDao idConnectionDao;
    @Autowired
    public LoginServiceImpl(IdConnectionDao idConnectionDao) {
        this.idConnectionDao = idConnectionDao;
    }

    @Override
    public String getConnection(com.wxy.eneity.Connection connection) {
        //判断用户传入的connection信息是否正确
        try {
            GetConnectionConfig.getConnection(connection);
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
            return "error";
        }
        //判断用户传入的connection是否为新连接
        String urlString = connection.getUrl();
        IdConnection idConnection = idConnectionDao.selectOne(new QueryWrapper<IdConnection>().eq("url", urlString));
        //不是新连接
        if(idConnection != null) {
            //判断用户是否修改过用户名和密码是更新并返回token信息
            if(!connection.getUsername().equals(idConnection.getUsername())||!connection.getPassword().equals(idConnection.getPassword())) {
                idConnectionDao.updateById(connection.getUsername(),connection.getPassword(),idConnection.getId());
            }
            return JwtConfig.getToken(idConnection.getId());
        }
        //是新连接
        int id=idConnectionDao.getMaxId()+1;
        int num = idConnectionDao.insert(new IdConnection(id,connection.getUrl(),connection.getUsername(),connection.getPassword()));
        if(num==0){
            return "error";
        }
        return JwtConfig.getToken(id);
    }
}
